package com.intexh.speedandroid.net.request;

import com.intexh.speedandroid.base.MainApplication;
import com.intexh.speedandroid.helper.UserHelper;
import com.intexh.speedandroid.net.interfaces.OnRequestCallBack;
import com.intexh.speedandroid.net.interfaces.OnUpLoadCallBack;
import com.intexh.speedandroid.utils.GsonUtils;
import com.intexh.speedandroid.utils.LogUtil;
import com.intexh.speedandroid.utils.ValidateUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求模式接口构建模式 1 好商城
 */
public enum RequestModel1 {

    INSTANCE;
    /**
     * @param api      请求接口
     * @param callBack
     */
    public void post(Object tag, final String api, final Map<String, String> params, final OnRequestCallBack callBack) {
        if (UserHelper.isLogin()) {//是否登录
            params.put("key",UserHelper.getCurrentToken());
        }
        params.put("client","android") ;
        OkGo.<String>post(api)//
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        success(response.body(), api, callBack, params,"post");
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        error(response.getException().toString(), api, params, callBack,"post");
                    }

                });

    }

    public void get(Object tag,final String api, final Map<String, String> params, final OnRequestCallBack callBack) {
        if (UserHelper.isLogin()) {//是否登录
            params.put("key",UserHelper.getCurrentToken());
        }
        params.put("client","android") ;
        OkGo.<String>get(api)//
                .tag(tag)
                .params(params)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        success(response.body(), api, callBack, params,"get");
                    }

                    @Override
                    public void onError(com.lzy.okgo.model.Response<String> response) {
                        error(response.getException().toString(), api, params, callBack,"get");
                    }

                });

    }

    private void error(String err,String api, Map<String, String> params, OnRequestCallBack callBack,String requestType) {
        if(err.contains("Unable to resolve host")){
            callBack.onError(-999,"网络连接失败，请检查您的网络");
        }else if(err.contains("Failed to connect")||err.contains("failed to connect")){
            callBack.onError(-998,"服务器连接失败，请稍后再试或联系客服");
        }else if(err.contains("timed out")||err.contains("timeout")){
            callBack.onError(-997,"请求超时,请重试");
        }else{
            callBack.onError(-996,err);
        }
        LogUtil.e("okhttp:", "*---------------------------------------------------------------------------*");
        LogUtil.e("okhttp:", "requestUrl("+requestType+"-mode1)= "+ api);
        LogUtil.e("okhttp:", "isSuccess = 请求错误" + err);
        LogUtil.e("okhttp:", "requestParams： " + GsonUtils.serializedToJson(params));
        LogUtil.e("okhttp:", "response= " + err);
        LogUtil.e("okhttp:", "*                                                                      *");

    }

    private void success(String s, String api, OnRequestCallBack callBack, Map<String, String> params,String requestType) {
        LogUtil.e("okhttp:", "*---------------------------------------------------------------------------*");
        LogUtil.e("okhttp:", "requestUrl("+requestType+"-mode1)= " + api);
        if (s == null) {
            LogUtil.e("okhttp:", "isSuccess = true 数据返回失败");
            print(s,params);
            callBack.onError(-1000,"数据返回空");
            return;
        }
        print(s, params);
        int code = GsonUtils.getIntFromJSON(s, "code");
        if (code==200) {
            LogUtil.e("okhttp:", "isSuccess = true 数据返回正常");
            callBack.onOk(GsonUtils.getStringFromJSON(s, "datas"));
        } else {
            String msg = GsonUtils.getStringFromJSON(s, "error");
            if("请登录".equals(msg)){
                //token失效
                MainApplication.showTokenInvalidHint();
                callBack.onError(code,"请登录");
            }else{
                if(ValidateUtils.isValidate(msg)){
                    LogUtil.e("okhttp:", "isSuccess = true 数据返回失败:"+msg);
                    callBack.onError(code,msg);
                }else{
                    callBack.onError(code,"数据返回异常:"+msg);
                }
            }
        }
    }

    private void print(String s, Map<String, String> params) {
        LogUtil.e("okhttp:", "requestParams： " + GsonUtils.serializedToJson(params));
        LogUtil.e("okhttp:", "response= " + s);
        LogUtil.e("okhttp:", "*----------------------------------------------------------------------------*");
    }

    public void upLoadFile(final String api, String key, File file, final OnUpLoadCallBack callBack) {
        final Map<String, String> params = new HashMap<>();
        params.put("key",UserHelper.getCurrentToken());
        params.put("client","android") ;
        OkGo.<String>post(api)//
                .isMultipart(true)       // 强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .params(params)        // 这里可以上传参数
                .params(key, file)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body();
                        int code = GsonUtils.getIntFromJSON(s, "code");
                        if (code==200) {
                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回正常");
                            print(s, params);
                            callBack.onOk(GsonUtils.getStringFromJSON(s, "datas"));
                        } else {
                            LogUtil.e("okhttp:", "isSuccess = 请求成功 数据返回失败");
                            print(s, params);
                            callBack.onError(code,GsonUtils.getStringFromJSON(s,"datas", "error"));
                        }
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        super.uploadProgress(progress);
                        LogUtil.e("frank","progress="+progress.toString());
                        callBack.upProgress((int) (progress.fraction * 100));
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        LogUtil.e("frank","onUpError="+response.body());
                        callBack.onError(-1,response.body());
                    }

                });
    }

}
